package com.example.common.domain.other;

import lombok.Data;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

@Data
public class RedisLock {
    private RedisTemplate<String, Object> redisTemplate;
    private String lockKey;
    private long expireTime; // 锁的过期时间(秒)

    public RedisLock(RedisTemplate<String, Object> redisTemplate, String lockKey, long expireTime) {
        this.redisTemplate = redisTemplate;
        this.lockKey = lockKey;
        this.expireTime = expireTime;
    }

    public boolean tryLock() {
        return Boolean.TRUE.equals(redisTemplate.opsForValue()
                .setIfAbsent(lockKey, "locked", expireTime, TimeUnit.SECONDS));
    }

    public void unlock() {
        redisTemplate.delete(lockKey);
    }
}
